package com.baseweb.webadmin.weixin.sign;

import java.security.MessageDigest;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import com.baseweb.webadmin.weixin.jssdk.JsapiTicketCache;
import com.baseweb.webadmin.weixin.utils.Constant;

/**
 *加载 cofing js时需要的签名
 * @author wcc
 *
 */
public class ConfingJsSign {
	private   static  Logger logeer = Logger.getLogger(ConfingJsSign.class);
	
	/**
	 * 获得 cofig js 签名
	 * @param request:此次请求作用域HttpServletRequest
	 * @return：成功返回签名结果集map ，失败返回null
	 *   <br> 
	 *      map  内部构造如下
	 *      map.put("url", url);
	        map.put("jsapi_ticket", jsapi_ticket);
	        map.put("nonceStr", nonce_str);
	        map.put("timestamp", timestamp);
	        map.put("signature", signature);
	        map.put("appid",appid);
	 */
	
	public static Map<String, String> getConfingJsSign(HttpServletRequest request){
		try {
			String jsapi_ticket = (String) JsapiTicketCache.jsapiTickemMap.get(Constant.JSAPI_TICKET);
			StringBuffer url = request.getRequestURL();
			String  queryString = request.getQueryString();
			if(queryString != null){
				url.append("?").append(queryString);
			}
			return sign(jsapi_ticket, url.toString());
		} catch (Exception e) {
			logeer.error("ConfingJsSign-->getConfingJsSign-->Exception",e);
		}
	    return  null;
	}
	
	
	/***
	 * 对    js cofing 签名
	 * @param jsapi_ticket  签名时需要的 jsapi_ticket
	 * @param url 访问的全路径 带参数
	 * @return  map  内部map构造如下<br> 
	 *      map.put("url", url);
	        map.put("jsapi_ticket", jsapi_ticket);
	        map.put("nonceStr", nonce_str);
	        map.put("timestamp", timestamp);
	        map.put("signature", signature);
	        map.put("appid",appid);
	 */
	 public static Map<String, String> sign(String jsapi_ticket, String url) {
	        Map<String, String> ret = new HashMap<String, String>();
	        String nonce_str = create_nonce_str();
	        String timestamp = create_timestamp();
	        String string1;
	        String signature = "";

	        //注意这里参数名必须全部小写，且必须有序
	        string1 = "jsapi_ticket=" + jsapi_ticket +
	                  "&noncestr=" + nonce_str +
	                  "&timestamp=" + timestamp +
	                  "&url=" + url;
	        
	        logeer.info("ConfingJsSign-->sign-->info"+string1);
	        try
	        {
	            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
	            crypt.reset();
	            crypt.update(string1.getBytes("UTF-8"));
	            signature = byteToHex(crypt.digest());
	        } catch (Exception e){
	        	 logeer.error("ConfingJsSign-->sign-->Exception",e);
	        }
	        ret.put("url", url);
	        ret.put("jsapi_ticket", jsapi_ticket);
	        ret.put("nonceStr", nonce_str);
	        ret.put("timestamp", timestamp);
	        ret.put("signature", signature);
	        ret.put("appid", Constant.WX_APPID);

	        return ret;
	    }

	    private static String byteToHex(final byte[] hash) {
	        Formatter formatter = new Formatter();
	        for (byte b : hash)
	        {
	            formatter.format("%02x", b);
	        }
	        String result = formatter.toString();
	        formatter.close();
	        return result;
	    }

	    private static String create_nonce_str() {
	        return UUID.randomUUID().toString();
	    }

	    private static String create_timestamp() {
	        return Long.toString(System.currentTimeMillis() / 1000);
	    }
	    
}
